import os
import json
import time

# from django.core.paginator import Paginator  # 注释掉Django分页器
from datetime import datetime
import dofile
from flask import Blueprint, request, render_template, jsonify, session, flash, redirect
from werkzeug.utils import secure_filename
import random
import verfy
from models import Homework, Uploadhomework, Teacher, Student,Copy
from collections import OrderedDict
from exts import db
import plagiaris_check as pc

from flask import Flask, render_template, request, jsonify
import torch
import torch.nn.functional as F
from transformers import BertTokenizer
import dpcnn
import os
import re
from docx import Document
import PyPDF2

bp = Blueprint("AI", __name__, url_prefix="/AI")

UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'docx'}


@bp.before_request
def before_request():
    """AI检测蓝图权限检查"""
    # 检查用户是否登录
    if session.get('is_login') != 'true':
        return redirect('/login')
    
    # AI检测功能对所有登录用户开放
    user_role = session.get('role')
    if user_role not in ['teacher', 'student']:
        return jsonify({'error': '用户角色无效'}), 403


THRESHOLDS = {
    'high_ai': 70,
    'medium_ai': 40,
    'human': 0
}

# 确保上传目录存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def generate_result(confidence):
    """根据置信度生成分级结果"""
    if confidence >= THRESHOLDS['high_ai']:
        level = "高度疑似AI生成"
        status = "ai_high"
        color = "#ff4444"
    elif THRESHOLDS['medium_ai'] <= confidence < THRESHOLDS['high_ai']:
        level = "中度疑似AI生成"
        status = "ai_medium"
        color = "#ff9900"
    else:
        level = "疑似人工撰写"
        status = "human_likely"
        color = "#00c851"
        
    return {
        "status": status,
        "message": f"{level}(置信度：{confidence:.1f}%)",
        "confidence": confidence,
        "level": level,
        "color": color,
        "details": {
            "ai_probability": confidence/100,
            "human_probability": 1 - confidence/100
        }
    }


@bp.route("/")
def student_index():
    return render_template('AI.html')

@bp.route('/api/ai-detection', methods=['POST'])
def ai_detection():
    try:
        # 1. 验证文件存在性
        if 'file' not in request.files:
            return jsonify({"error": "未选择文件"}), 400
            
        file = request.files['file']
        
        # 2. 验证文件有效性
        if file.filename == '':
            return jsonify({"error": "空文件名"}), 400
            
        if not allowed_file(file.filename):
            return jsonify({"error": "不支持的文件类型"}), 400

        # 3. 安全保存文件
        filename = secure_filename(file.filename)
        save_path = os.path.join(UPLOAD_FOLDER, filename)
        file.save(save_path)

        # 4. 模拟检测逻辑（实际应替换为模型推理）
        # 生成偏向人工撰写的随机置信度（0-100）
        # 使用贝塔分布使结果偏向人工（α=2, β=5）
        raw_confidence = random.betavariate(2, 5) * 100
        confidence = min(100, max(0, raw_confidence))  # 确保在0-100范围内

        # 5. 生成分级结果
        result = generate_result(confidence)
        result['filename'] = filename
        
        return jsonify(result)
        
    except Exception as e:
        return jsonify({
            "error": str(e),
            "error_code": "INTERNAL_ERROR"
        }), 500